<?php
class Wee_Logging_Model_Archive extends Varien_Object{
    protected $_file = '';
    public function getBasePath(){
        return BP . DS . 'var' . DS . 'logging' . DS . 'archive';
    }
    protected function _validateBaseName($baseName){
        return (bool)preg_match('/^[0-9]{10}\.csv$/', $baseName);
    }
    public function loadByBaseName($baseName){
        $this -> _file = '';
        $this -> unsBaseName();
        if (!$this -> _validateBaseName($baseName)){
            return $this;
        }
        $filename = $this -> generateFilename($baseName);
        if (!file_exists($filename)){
            return $this;
        }
        $this -> setBaseName($baseName);
        $this -> _file = $filename;
        return $this;
    }
    public function generateFilename($baseName){
        return $this -> getBasePath() . DS . substr($baseName, 0, 4) . DS . substr($baseName, 4, 2) . DS . $baseName;
    }
    public function getFilename(){
        return $this -> _file;
    }
    public function getContents(){
        if ($this -> _file){
            return file_get_contents($this -> _file);
        }
        return '';
    }
    public function getMimeType(){
        return 'text/csv';
    }
    public function createNew($baseName = ''){
        if (!$baseName){
            $baseName = date('YmdH') . '.csv';
        }
        if (!$this -> _validateBaseName($baseName)){
            return false;
        }
        $file = new Varien_Io_File();
        $filename = $this -> generateFilename($baseName);
        $file -> setAllowCreateFolders(true) -> createDestinationDir(dirname($filename));
        unset($file);
        if (!touch($filename)){
            return false;
        }
        $this -> loadByBaseName($baseName);
        return true;
    }
}
